#include<iostream>
#include<unistd.h>
#include<queue>
#include<pthread.h>

using namespace std;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER; //定义条件变量，为了保证访问临界资源的同步性
int cnt = 0;

//目的：想要让多个线程同步互斥去对cnt++，让线程按照特定的次序去访问临界资源
void* Count(void* args)
{
    //让该线程挂起，执行完毕后自动释放
    pthread_detach(pthread_self());
    uint64_t i = (uint64_t)args;
    cout << "thread-" << i <<endl;

    while(true)
    {
        pthread_mutex_lock(&mutex);
        //某个线程一旦申请所资源成功，让他去等待队列去等待，所以谁先申请成功，谁先去等待队列等待
        //pthread_cond_wait在等待的时候会自动让锁资源释放
        pthread_cond_wait(&cond, &mutex);

        cout << "thread-" << i <<", cnt: " << cnt++ << endl;
        sleep(1);

        pthread_mutex_unlock(&mutex);
    }

    return nullptr;
}

int main()
{
    for(int i=1; i<=5; i++)
    {
        pthread_t tid;
        pthread_create(&tid, nullptr, Count, (void*)i);
        usleep(1000);
    }
    
    sleep(3);
    cout << "main thread begin: " << endl;

    while(true) 
    {
        sleep(1);
        //pthread_cond_signal唤醒在等待队列中的线程，默认是第一个
        pthread_cond_signal(&cond);
        cout << "signal wake one thread..." << endl;
    }

    return 0;
}